package com.cqeec.action;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.cqeec.bean.ResultMessage;
import com.cqeec.bean.UserInfo;
import com.cqeec.util.DBUtil;
import com.cqeec.util.MD5;
/**
 * 
 * @author HuaL
 * @description 系统用户控制器
 */
public class UserAction {
	Connection con = null;

	public UserAction() {
		con = DBUtil.getConnection();
	}
	/**
	 * @description 修改用户密码
	 * @param new_pwd 新密码
	 * @param userid  用户id
	 * @return 修改成功返回true，失败返回false
	 */
	public boolean EditPassword(String new_pwd,int userid){
		String sql = "update userInfo set userpwd=? where userid=?";
		try {
			PreparedStatement pstm = con.prepareStatement(sql);
			pstm.setString(1, new_pwd);
			pstm.setInt(2, userid);
			pstm.executeUpdate();
			pstm.close();
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			return false;
		}
	}
	
	/**
	 * @description 用户登录验证
	 * @param userInfo 登录用户对象
	 * @return 返回一个ResultMessage对象,里面包含验证的代码值以及UserInfo对象 
	 * 代码值 0:成功  -1：用户名错误  -2：密码错误  -3:系统错误
	 */
	public ResultMessage Login(UserInfo userInfo){
		ResultMessage resultMessage = new ResultMessage();
		String sql = "select * from UserInfo where username=?";
		try {
			PreparedStatement pstm = con.prepareStatement(sql);
			pstm.setString(1, userInfo.getUsername());
			ResultSet rs = pstm.executeQuery();
			if (rs.next()){
				if (rs.getString("userpwd").equals(MD5.MD5Encode(userInfo.getUserpwd()))){
					resultMessage.setResultCode(0);
					userInfo.setUserid(rs.getInt("userid"));
					userInfo.setRealname(rs.getString("realname"));
					userInfo.setUsertype(rs.getInt("usertype"));
					resultMessage.setUserInfo(userInfo);
					rs.close();
					pstm.close();
				}else{
					resultMessage.setResultCode(-2);
					rs.close();
					pstm.close();
				}
			}else{
				resultMessage.setResultCode(-1);
				rs.close();
				pstm.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			resultMessage.setResultCode(-3);
		}
		return resultMessage;
	}
}
